using System;
using System.Collections.Generic;
using System.Text;

using System.IO;
using System.Net;
using System.Net.Sockets;

using System.Configuration;

namespace LoggingClient.NetworkLog
{
    public class LogClient
    {

        private static LogClient LOGClientInstance = null;
        public static LogClient Instance
        {
            get
            {
                if (null == LOGClientInstance)
                {
                    LOGClientInstance = new LogClient();
                }

                return LOGClientInstance;
            }
        }


        private static Socket socketClient = null;
        IPEndPoint IPAddressEndP = null;

        private void Init()
        {
            IPAddress address;

            string IPStr = "127.0.0.1";//"84.203.44.15";//ConfigurationManager.AppSettings["LogServerIP"].ToString();

            if (!IPAddress.TryParse(IPStr, out address))
            {
                throw new Exception("Invalid IP address!");
            }

            IPAddressEndP = new IPEndPoint(address, 9082);

            socketClient = new Socket(IPAddressEndP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        }


        public void WriteLine(string Str)
        {
            try
            {
                if (null == socketClient || null == IPAddressEndP)
                {
                    Init();
                }

                if (!socketClient.Connected)
                {
                    socketClient.Connect(IPAddressEndP);
                }

                byte[] content = Encoding.UTF8.GetBytes(Str);
                byte[] LenInfo = new byte[2];
                if (content == null)
                {
                    LenInfo[0] = 0;
                    LenInfo[1] = 0;
                }
                else if (content.Length == 1)
                {
                    LenInfo[0] = (byte)(content.Length / 256);
                    LenInfo[1] = 0;
                }
                else
                {
                    LenInfo[0] = (byte)(content.Length / 256);
                    LenInfo[1] = (byte)(content.Length % 256);
                }

                socketClient.Send(LenInfo);
                socketClient.Send(content);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}
